﻿using System.Security.Claims;
using Core.Authorization;
using Core.Interfaces.Users;
using Microsoft.AspNetCore.Http;

namespace Infrastructure.Identity.Users;

public class CurrentUserService : ICurrentUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    private ClaimsPrincipal? User => _httpContextAccessor.HttpContext?.User;

    public string? Name => IsAuthenticated() ? User?.Identity?.Name : null;

    public string? GetUserEmail()
    {
        if (!IsAuthenticated()) return null;
        return User?.GetEmail();
    }

    public bool IsAuthenticated() => User?.Identity?.IsAuthenticated is true;

    public bool IsSuperAdmin => User?.GetIsSuperAdmin() is true;

    public bool IsInRole(string role) => User?.IsInRole(role) is true;

    public IEnumerable<Claim>? GetUserClaims() => User?.Claims;

    public string? GetTenant()
    {
        if (!IsAuthenticated()) return null;
        return User?.GetTenant(); 
    }

    public Guid GetUserId()
    {
        if (!IsAuthenticated())
            return Guid.Empty;

        var userIdValue = User?.GetUserId(); 
        if (string.IsNullOrEmpty(userIdValue))
            return Guid.Empty;

        return Guid.TryParse(userIdValue, out var userId) ? userId : Guid.Empty;
    }

    public bool IsInPermission(string permission)
    {
        var permissions = User?.GetPermissions();
        if (permissions == null || !permissions.Any())
            return false;

        return permissions.Contains(permission);
    }
}
